<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>

<body>
	<button>节流按钮</button>
	<script>
		var btn = document.querySelector('button')
		// btn.onclick = function () {}

		function fn() {
			console.log("节流函数触发")
		}
		// 要立即触发，最后一次触发调用
		function throttle(callback, wait = 2000) {
			let timeoutid;
			let old = 0;
			return function () {
				let now = new Date().getTime();
				if (now - old > wait || old == 0) {
					callback.apply(this, arguments)
					old = now;
				} else {
					if (!timeoutid) {
						timeoutid = setTimeout(() => {
							callback.apply(this, arguments)
							timeoutid = null;
						}, wait);
					} else {
						console.log("出于节流状态，不执行函数")
					}
				}
			}
		}
		btn.onclick = throttle(fn)
	</script>
</body>

</html>